package com.imooc.ad.index;

import com.imooc.ad.index.keyword.UnitKeywordIndex;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *  索引服务缓存服务
 *  ApplicationContextAware：应用程序上下文，得到spring容器中初始化的组件
 *  PriorityOrdered：优先级排序，优先初始化已排序的应用程序
 *  使用：注入DataTable类，调用DataTable.of(UnitKeywordIndex.class);
 */
@Component
public class DataTable implements ApplicationContextAware, PriorityOrdered {

    private static ApplicationContext applicationContext;

    //保存所有Index索引
    public static final Map<Class, Object> dataTableMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        DataTable.applicationContext = applicationContext;
    }

    //定义最高优先级，优先初始化
    @Override
    public int getOrder() {
        return PriorityOrdered.HIGHEST_PRECEDENCE;
    }

    //根据索引class类型获取索引服务类
    @SuppressWarnings("all")
    public static <T> T of(Class<T> classs) {

        T instance = (T) dataTableMap.get(classs);
        if (null != instance) {
            return instance;
        }

        //存放索引的dataTableMap为空，通过bean(classs)获取索引bean
        dataTableMap.put(classs, bean(classs));
        return (T) dataTableMap.get(classs);
    }

    //根据beanName获取spring容器中的bean
    @SuppressWarnings("all")
    private static <T> T bean(String beanName) {
        return (T) applicationContext.getBean(beanName);
    }

    //根据class类型获取spring容器中的bean
    @SuppressWarnings("all")
    private static <T> T bean(Class classs) {
        return (T) applicationContext.getBean(classs);
    }
}
